<?php
// +----------------------------------------------------------------------
// | ZZYY  [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2023 https://www.fastadmin.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: 乘风
// +----------------------------------------------------------------------

namespace app\admin\controller\zzyy;

use addons\zzyy\library\SaasCenter;
use addons\zzyy\module\Weixin;
use app\admin\model\zzyy\ZzyyReserve;
use app\admin\model\zzyy\ZzyyTransaction;
use app\admin\model\zzyy\ZzyyUserBalance;
use app\admin\model\zzyy\ZzyyUserExtend;
use app\common\controller\Backend;
use think\Db;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Reserve extends Backend
{

    /**
     * ZzyyReserve模型对象
     * @var \app\admin\model\zzyy\ZzyyReserve
     */
    protected $model = null;

    protected $_ispInfo = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\zzyy\ZzyyReserve;
        $this->assign("payWayList", $this->model->getPayWayList());
        $this->assign("statusList", $this->model->getStatusList());
        $this->_ispInfo = SaasCenter::getOpenPlatformMerchantIsp();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['store','room', 'user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function ajaxCancelReserve()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->get('id');
            $reserve = ZzyyReserve::get($id, ['room']);

            Db::startTrans();

            try {
                if (ZzyyReserve::PAY_WAY_BALANCE == $reserve->pay_way) { // 余额支付

                    $userExtend = ZzyyUserExtend::where('user_id', $reserve->user_id)->find();
                    $afterValue = $userExtend->balance + $reserve->fee;

                    ZzyyUserBalance::create([
                        'user_id' => $reserve->user_id,
                        'type' => ZzyyUserBalance::TYPE_SYSTEM_REFUND, //系统返还
                        'value' => $reserve->fee,
                        'before_value' => $userExtend->balance,
                        'after_value' => $afterValue,
                        'createtime' => time(),
                        'updatetime' => time()
                    ]);

                    $userExtend->balance = $afterValue;
                    $userExtend->save();

                } else if (ZzyyReserve::PAY_WAY_DIRECT == $reserve->pay_way) { // 微信支付

                    $trans = ZzyyTransaction::get($reserve->transaction_id);

                    // 退款接口多次请要都可以
                    $result = Weixin::getInstance()->refunds($trans->transaction_no, $trans->out_trade_no, $trans->fee, $trans->fee);

                    if (isset($result['transaction_id'])) {
                        $trans->status = ZzyyTransaction::STATUS_REFUND; // 标识为退款
                        $trans->save();
                    } else if ('FAIL' == $result['return_code']) {  // 微信支付平台报错
                        throw new \Exception($result['return_msg']);
                    } else {
                        throw new \Exception('出现服务器错误，请联系管理员');
                    }

                } else if (ZzyyReserve::PAY_WAY_OTHER == $reserve->pay_way) { //其它支付   0元支付

                }

                // 标记Reserve是取消了
                $reserve->status = ZzyyReserve::STATUS_CANCELLED;
                $reserve->save();

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('当前预约取消成功');
        }
        $this->error('error');
    }


}